'use strict';
var _l = require('lodash');
var vk; // 全局vk实例
// 涉及的表名
const dbName = {
    //test: "vk-test", // 测试表
};

var db = uniCloud.database(); // 全局数据库引用
var _ = db.command; // 数据库操作符
var $ = _.aggregate; // 聚合查询操作符
/**
 * 权限注意：访问以下链接查看
 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
 */
var cloudObject = {
    isCloudObject: true, // 标记为云对象模式
    /**
     * 请求前处理，主要用于调用方法之前进行预处理，一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。
     * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#before-预处理
     */
    _before: async function () {
        vk = this.vk; // 将vk定义为全局对象
        // let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包
    },
    /**
     * 请求后处理，主要用于处理本次调用方法的返回结果或者抛出的错误
     * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#after-后处理
     */
    _after: async function (options) {
        let {
            err,
            res
        } = options;
        if (err) {
            return; // 如果方法抛出错误，直接return;不处理
        }
        return res;
    },
    /**
     * 获取列表
     * @url client/pub.js.getList 前端调用的url参数地址
     */
    getList: async function (data) {
        let res = {
            code: 0,
            msg: ''
        };
        let {
            uid
        } = this.getClientInfo(); // 获取客户端信息
        // 业务逻辑开始-----------------------------------------------------------


        // 业务逻辑结束-----------------------------------------------------------
        return res;
    },
    //获取离最近一天的三场拍卖
    getlimitPlaces: async function (data) {
        let res = {
            code: 0,
            msg: ''
        };
        // 业务逻辑开始-----------------------------------------------------------
        let dbName = "bidding-places";
        res = await vk.baseDao.selects({
            dbName,
            whereJson: {
                is_on: true
            },
            sortArr: [{
                "name": "sort",
                "type": "asc"
            }],
        });
        return res;

    },
    getCategoriesListByPlaceid: async function (data) {
        let res = await vk.baseDao.selects({
            dbName: "bidding-booths",
            pageIndex: 1,
            pageSize: 10,
            // 主表where条件
            whereJson: {
                location: data.placeid,
            },
            groupJson: {
                _id: "$category_id", // _id是分组id（_id:为固定写法，必填属性），这里指按user_id字段进行分组
                category_id: _.$.first("$category_id"), // 这里是为了把user_id原样输出

            },
            // 副表列表
            foreignDB: [{
                dbName: "bidding-categories",
                localKey: "category_id",
                foreignKey: "_id",
                as: "categories",
                sortArr: [{
                    "name": "sort",
                    "type": "asc"
                }],
                limit: 1
            }],
            lastWhereJson: {
                _id: _.neq(null)
            }
        })
        res.rows = res.rows.map(x => x.categories);
        res.rows = _l.sortBy(res.rows, x => x.sort)
        return res;
    },
    getCategoriesList: async function (data) {
        let res = {
            code: 0,
            msg: ''
        };
        // 业务逻辑开始-----------------------------------------------------------
        // let dbName = "bidding-categories";
        // res = await vk.baseDao.getTableData({
        //     dbName,
        //     data,
        //     sortArr: [{
        //         "name": "sort",
        //         "type": "asc"
        //     }],
        // });
        // return res;

        res = await vk.baseDao.selects({
            dbName: "bidding-categories",
            pageIndex: 1,
            pageSize: -1,
            whereJson: {
                is_on: true,
            },
            sortArr: [{
                "name": "sort",
                "type": "asc"
            }],
        })
        return res;
    },
    getBoothsList: async function (data) {
        let res = {
            code: 0,
            msg: ''
        };
        // 业务逻辑开始-----------------------------------------------------------
        let dbName = "bidding-booths";
        res = await vk.baseDao.getTableData({
            dbName,
            data,
            whereJson: { // 条件
                status: _.in([0, 1, 2]),
                is_on_sale: true,
            },
            foreignDB: [{
                dbName: "bidding-biddingprices", // 副表名
                localKey: "_id", // 主表外键字段名
                foreignKey: "booth_id", // 副表外键字段名
                as: "biddingList",
                whereJson: { // 条件
                    status: _.neq(-1)
                },
                limit: 200, // 当limit = 1时，以对象形式返回，否则以数组形式返回
                // 副表字段显示规则
                fieldJson: {},
                // 副表排序规则
                sortArr: [{
                    "name": "sort",
                    "type": "asc"
                }, {
                    "name": "nowPrice",
                    "type": "desc"
                },
                ],

            },
            {
                dbName: "bidding-session", // 副表名
                localKey: "location", // 主表外键字段名
                foreignKey: "place_id", // 副表外键字段名
                as: "sessions",
                limit: 10, // 当limit = 1时，以对象形式返回，否则以数组形式返回
            }
            ],
            lastSortArr: [{
                "name": "sort",
                "type": "asc"
            },
            {
                "name": "nowPrice",
                "type": "desc"
            },
            ]
        });
        return res;
    },
    getServicesList: async function (data) {
        let res = {
            code: 0,
            msg: ''
        };
        res.row  = await vk.baseDao.selects({
            dbName: "cs-services", // 主表名
            getMain: true,
            whereJson: {
                isEnable: true
            },
        });
        return res;
    },
    getServiceByID: async function (data) {
        let res = {
            code: 0,
            msg: ''
        };
        res.data = await  vk.baseDao.findById({
            dbName: "cs-services",
            id: data._id
        });
        return res;
    },

    getSessionByPlace: async function (data) {
        let res = {
            code: 0,
            msg: ''
        };
        // 业务逻辑开始-----------------------------------------------------------
        let dbName = "bidding-session";
        return await vk.baseDao.select({
            dbName: dbName, // 表名
            getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
            pageIndex: 1, // 当前第几页
            pageSize: 3, // 每页条数
            whereJson: { // 条件
                status: _.in([0, 1, 2]),
                place_id: data.place_id
            },
            sortArr: [{
                "name": "start",
                "type": "asc"
            }],
        });


    },

    getsysinfo: async function (data) {
        let res = {
            code: 0,
            msg: ''
        };
        // 业务逻辑开始-----------------------------------------------------------
        let dbName = "sys-info";
        res = await vk.baseDao.getTableData({
            getOne: true,
            dbName,
            data
        });
        return res;
    },

    /**
     * 模板函数
     * @url client/pub.js.test 前端调用的url参数地址
     */
    test: async function (data) {
        let res = {
            code: 0,
            msg: ''
        };
        let places = await vk.baseDao.select({
            dbName: "bidding-places", // 表名
            getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
            getMain: true, // 是否只返回rows数据，默认false
            pageIndex: 1, // 当前第几页
            pageSize: -1, // 每页条数
            whereJson: { // 条件
                is_on: true,
                dateArr: _.neq(null),
                bingtimes: _.neq(null)
            }
        });

        for (var i = 0; i < places.length; i++) {
            let place = places[i];

            //找出待命和进行中的
            let stand = await vk.baseDao.select({
                dbName: "bidding-session",
                pageIndex: 1,
                getMain: true,
                pageSize: 20,
                whereJson: {
                    place_id: place._id,
                    status: _.in([1, 2])
                }
            });
            // console.log(stand)
            if (vk.pubfn.isNull(stand)) {
                let session = await vk.baseDao.select({
                    dbName: "bidding-session", // 表名
                    getOne: true, // 是否需要同时查询满足条件的记录总数量，默认false
                    getMain: true, // 是否只返回rows数据，默认false
                    pageIndex: 1, // 当前第几页
                    pageSize: 10, // 每页条数
                    whereJson: { // 条件
                        status: 0,
                        place_id: place._id
                    },
                    sortArr: [{
                        "name": "start",
                        "type": "asc"
                    }],
                });
                //console.log(session)
                //更新
                if (!vk.pubfn.isNull(session)) {
                    await vk.baseDao.updateById({
                        dbName: 'bidding-session',
                        id: session._id,
                        dataJson: {
                            status: 1
                        }
                    });
                }
            } else {

                let now = stand.find(x => x.status == 1)

                if (!vk.pubfn.isNull(now)) {
                    let time = Date.now();
                    let selectRes = await vk.baseDao.select({
                        dbName: "bidding-session",
                        pageIndex: 1,
                        getMain: true,
                        pageSize: 200,
                        whereJson: {
                            _id: now._id,
                            start: _.lte(time),
                            end: _.gte(time)
                        }
                    });
                    console.log('-----')
                    console.log(selectRes)
                    console.log('-----')
                    if (!vk.pubfn.isNull(selectRes)) {

                        let num = await vk.baseDao.updateById({
                            dbName: 'bidding-session',
                            id: now._id,
                            dataJson: {
                                status: 2
                            }
                        });
                    }
                }

            }
        }

    },


    test2: async function (data) {

        // await vk.baseDao.del({
        //     dbName: "bidding-session",
        //     whereJson: {
        //         _id: _.exists(true),
        //     }
        // });
        let places = await vk.baseDao.select({
            dbName: "bidding-places", // 表名
            getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
            getMain: true, // 是否只返回rows数据，默认false
            pageIndex: 1, // 当前第几页
            pageSize: -1, // 每页条数
            whereJson: { // 条件
                is_on: true,
                dateArr: _.neq(null),
                bingtimes: _.neq(null)
            }
        });
        let addpush = [];
        for (var i = 0; i < places.length; i++) {
            let place = places[i];
            let days = listDates(place.dateArr);
            if (days != undefined && days.length > 0) {
                for (var j = 0; j < days.length; j++) {
                    for (var k = 0; k < place.bingtimes.length; k++) {

                        if (place.bingtimes[k] != undefined) {
                            let no =
                                `${place._id}${days[j]}${place.bingtimes[k].code[0]}${place.bingtimes[k].code[1]}`;
                            let find = await vk.baseDao.findByWhereJson({
                                dbName: "bidding-session",
                                whereJson: {
                                    no: no
                                }
                            });

                            if (find == null) {
                                let start = new Date(`${days[j]} ${place.bingtimes[k].code[0]}:00+08:00`).getTime()

                                let addobj = {
                                    place_id: place._id,
                                    no: `${place._id}${days[j]}${place.bingtimes[k].code[0]}${place.bingtimes[k].code[1]}`,
                                    place_name: place.name,
                                    status: 0,
                                    start: start,
                                    start_str: `${days[j]} ${place.bingtimes[k].code[0]}`,
                                    end: new Date(`${days[j]} ${place.bingtimes[k].code[1]}:00+08:00`).getTime(),
                                    end_str: `${days[j]} ${place.bingtimes[k].code[1]}`,
                                }
                                addpush.push(addobj)
                            }
                        }
                    }
                }
            }
        }
        let addids = ''
        if (addpush.length > 0) {
            addids = await vk.baseDao.adds({
                dbName: "bidding-session", // 表名
                dataJson: addpush
            });
        }

        function listDates(array) {
            // 定义一个空数组，用于存放结果
            let result = [];
            // 使用Date对象，将数组中的日期字符串转换为日期对象
            let startDate = new Date(array[0]);
            let endDate = new Date(array[1]);
            // 使用一个循环，从开始日期到结束日期，每次增加一天
            for (let date = startDate; date <= endDate; date.setDate(date.getDate() + 1)) {
                // 将每个日期对象转换为日期字符串，格式为yyyy-mm-dd
                let dateString = date.toISOString().slice(0, 10);
                // 将日期字符串添加到结果数组中
                result.push(dateString);
            }
            // 返回结果数组
            return result;
        }

        // 业务逻辑结束-----------------------------------------------------------
        return {
            code: 0,
            msg: addids
        }
    }
};
module.exports = cloudObject;